package com.example.demo.config;

import com.example.demo.model.Book;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;
import java.util.Objects;

/**
 * 功能描述：
 *
 * @Author: Zhanghf
 * @Date: 2021/12/13 8:50
 */
@Configuration
public class RedisConfig {
    @Primary
    @Bean("BookManager")
    public CacheManager BookManager(RedisTemplate redisTemplate) {
        return new RedisCacheManager(
                RedisCacheWriter
                        .nonLockingRedisCacheWriter(Objects
                                .requireNonNull(redisTemplate
                                        .getConnectionFactory())),
                RedisCacheConfiguration
                        .defaultCacheConfig()
                        .entryTtl(Duration.ofDays(1)) // 设置缓存过期时间为一天
                        .serializeValuesWith(
                                RedisSerializationContext
                                        .fromSerializer(new GenericJackson2JsonRedisSerializer())
                                        // .fromSerializer(new Jackson2JsonRedisSerializer<>(Book.class))
                                        .getValueSerializationPair()));
    }

}
